"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
let mainWindow = null;
function createWindow() {
    mainWindow = new electron_1.BrowserWindow({
        width: 1000,
        height: 700,
        webPreferences: {
            contextIsolation: true, // 推荐开启，安全
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: false,
        }
    });
    if (process.env.VITE_DEV_SERVER_URL) {
        // 开发模式：加载 vite dev server
        mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
        mainWindow.webContents.openDevTools();
    }
    else {
        // 生产模式：加载打包好的文件
        mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
    }
    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}
// 监听渲染进程发来的读取文件夹请求
electron_1.ipcMain.handle('read-directory', async (event, dirPath) => {
    try {
        const dirents = await fs.promises.readdir(dirPath, { withFileTypes: true });
        const entries = await Promise.all(dirents.map(async (dirent) => {
            const fullPath = path.join(dirPath, dirent.name);
            const stats = await fs.promises.stat(fullPath);
            const parentPath = path.dirname(fullPath);
            return {
                name: dirent.name,
                path: fullPath,
                parentPath: parentPath,
                isFile: dirent.isFile(),
                isDirectory: dirent.isDirectory(),
                size: stats.size,
                createdAt: stats.birthtime,
                updatedAt: stats.mtime
            };
        }));
        return { success: true, data: entries };
    }
    catch (error) {
        return { success: false, message: error.message };
    }
});
// 创建文件夹
electron_1.ipcMain.handle('create-folder', async (_, parentPath, folderName) => {
    const fullPath = path.join(parentPath, folderName);
    try {
        if (!fs.existsSync(fullPath)) {
            fs.mkdirSync(fullPath);
            return { success: true, data: fullPath };
        }
        else {
            return { success: false, error: '文件夹已存在' };
        }
    }
    catch (error) {
        return { success: false, error: error.message };
    }
});
// 重命名文件夹
electron_1.ipcMain.handle('rename-folder', async (_, oldPath, newName) => {
    try {
        const newPath = path.join(path.dirname(oldPath), newName);
        fs.renameSync(oldPath, newPath);
        return { success: true, data: newPath };
    }
    catch (error) {
        return { success: false, error: error.message };
    }
});
electron_1.ipcMain.handle('delete-folder', async (_, folderPath) => {
    try {
        // 递归删除文件夹（包含子文件和文件夹）
        await fs.promises.rm(folderPath, { recursive: true, force: true });
        return { success: true };
    }
    catch (error) {
        return { success: false, error: error.message };
    }
});
electron_1.ipcMain.handle('search-in-directory', async (_, rootPath, keyword) => {
    const results = [];
    async function searchDir(currentPath) {
        try {
            const dirents = await fs.promises.readdir(currentPath, { withFileTypes: true });
            for (const dirent of dirents) {
                const fullPath = path.join(currentPath, dirent.name);
                const matches = dirent.name.includes(keyword);
                const isDir = dirent.isDirectory();
                if (matches) {
                    results.push({
                        name: dirent.name,
                        path: fullPath,
                        parentPath: currentPath,
                        isFile: dirent.isFile(),
                        isDirectory: isDir,
                    });
                }
                if (isDir) {
                    await searchDir(fullPath); // 递归搜索子目录
                }
            }
        }
        catch (err) {
            console.error(`搜索目录时出错: ${currentPath}`, err);
        }
    }
    await searchDir(rootPath);
    return { success: true, data: results };
});
electron_1.ipcMain.handle('open-file-external', async (_, filePath) => {
    try {
        await electron_1.shell.openPath(filePath); // 自动使用系统默认程序打开文件
        return { success: true };
    }
    catch (err) {
        return { success: false, error: err.message };
    }
});
electron_1.ipcMain.handle('get-folder-steps', async (_, rootPath, targetPath) => {
    try {
        const relative = path.relative(rootPath, targetPath);
        if (relative.startsWith('..'))
            throw new Error('targetPath is not inside rootPath');
        const segments = relative.split(path.sep).filter(Boolean);
        const result = [];
        let current = rootPath;
        for (const segment of segments) {
            current = path.join(current, segment);
            result.push(current);
        }
        return { success: true, data: result };
    }
    catch (err) {
        return { success: false, error: err.message };
    }
});
const writeStreams = new Map();
electron_1.ipcMain.on('upload-chunk', (event, { name, path: dir, chunk, isFirst, isLast }) => {
    debugger;
    const fullPath = path.join(dir, name);
    if (isFirst) {
        // 如果已存在，重命名
        let finalPath = fullPath;
        let index = 1;
        const { name: baseName, ext } = path.parse(name);
        while (fs.existsSync(finalPath)) {
            finalPath = path.join(dir, `${baseName}(${index++})${ext}`);
        }
        const stream = fs.createWriteStream(finalPath, { flags: 'w' });
        writeStreams.set(name, stream);
        stream.write(Buffer.from(chunk));
    }
    else {
        const stream = writeStreams.get(name);
        if (stream) {
            stream.write(Buffer.from(chunk));
        }
    }
    if (isLast) {
        const stream = writeStreams.get(name);
        if (stream) {
            stream.end();
            writeStreams.delete(name);
        }
    }
});
electron_1.app.whenReady().then(() => {
    createWindow();
    electron_1.app.on('activate', () => {
        if (electron_1.BrowserWindow.getAllWindows().length === 0)
            createWindow();
    });
});
// 关闭所有窗口时退出（macOS 除外）
electron_1.app.on('window-all-closed', () => {
    if (process.platform !== 'darwin')
        electron_1.app.quit();
});
